/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/***************************************************************************
 * Name: shared_state.h
 *
 * Purpose: Implementation shared state for Future/Promise
 *
 * Developer:
 *   wen.gu , 2022-08-23
 *
 * TODO:
 *
 ***************************************************************************/

#ifndef __DOG_CORE_INTERNAL_SHARED_STATE_H__
#define __DOG_CORE_INTERNAL_SHARED_STATE_H__
/******************************************************************************
 **    INCLUDES
 ******************************************************************************/
#include <memory>
#include <mutex>
#include <thread>
#include <type_traits>
#include <condition_variable>
#include <vector>

#include "dog/core/error_code.h"
#include "dog/core/result.h"
#include "dog/core/future_error_domain.h"

/******************************************************************************
 **    MACROS
 ******************************************************************************/


/******************************************************************************
 **    TYPE DEFINITIONS
 ******************************************************************************/
namespace dog {
namespace core {


/** Specifies the state of a Future as returned by wait_for() and wait_until(). These definitions are equivalent to the
 *  ones from std::future_status. However, no item equivalent to std::future_status::deferred is available here.
 *  The numerical values of the enum items are implementation-defined
*/
enum class FutureStatus : uint8_t {
    none,  /** default value */
    ready, /** the shared state is ready */
    timeout, /** the shared state did not become ready before the specified timeout has passed */
    retrived,
};


namespace internal {

/******************************************************************************
 **    CLASSES/FUNCTIONS DEFINITIONS
 ******************************************************************************/

template<typename T, typename E = ErrorCode>
class FutureSharedState {
public:
    using ContinuationFunc = std::function<void()>;
    using Copyable  = std::is_copy_constructible<T>;
    using Movable   = std::is_move_constructible<T>;  
    using ValueType = Result<T, E>;
    using AutoLock = std::unique_lock<std::mutex>;
public:
    static_assert(Copyable() || Movable(), "must be copyable or movable or void");
    FutureSharedState(): mState(FutureStatus::none), mHasRetrieved(false) { }

public:
    void wait() {
        std::unique_lock<std::mutex> lock(mThenMtx);
        mCond.wait(lock, [this]() { return mState != FutureStatus::none; });
    }

    template <typename Rep, typename Period>
    FutureStatus waitFor(const std::chrono::duration<Rep, Period> &timeout_duration)  {
        std::unique_lock<std::mutex> lock(mThenMtx);
        bool r = mCond.wait_for(lock, timeout_duration, [this]() { return mState != FutureStatus::none; });
        if(!r){ mState = FutureStatus::timeout; }
        return mState;
    }

    template <typename Clock, typename Duration>
    FutureStatus waitUntil(const std::chrono::time_point<Clock, Duration> &timeout_time)  {
        std::unique_lock<std::mutex> lock(mThenMtx);
        bool r = mCond.wait_until(lock, timeout_time, [this]() { return mState != FutureStatus::none; });
        if(!r){ mState = FutureStatus::timeout; }
        return mState;
    }

public:
    void setResult(ValueType&& val) {
        AutoLock lock(mThenMtx);
        if (mState != FutureStatus::none) { return; }

        mState = FutureStatus::ready;
        mValue = std::move(val);
        mCond.notify_all();

        std::vector<std::function<void()>> continuations = std::move(mContinuations);
        lock.unlock();

        for(auto const& continuation : continuations) {
            if(continuation) { continuation(); }
        }
    }

    ValueType getResult() {
        {
            AutoLock lock(mThenMtx);
            switch (mState) {
            case FutureStatus::none: break;
            case FutureStatus::timeout: return ValueType::FromError(future_errc::no_state); break;
            case FutureStatus::ready: {
                mState = FutureStatus::retrived;
                return std::move(mValue);
            }
            default: return ValueType::FromError(future_errc::future_already_retrieved); break;
            }
        }
        wait();
        AutoLock lock(mThenMtx);
        return std::move(mValue);
    }

private:
    FutureStatus mState;
    std::mutex mThenMtx;
    std::condition_variable mCond;
    std::atomic<bool> mHasRetrieved;
    ValueType mValue;
    std::vector<ContinuationFunc> mContinuations;
};

} /** namespace internal */
} /** namespace core */
} /** namespace dog */
#endif /** !__DOG_CORE_INTERNAL_SHARED_STATE_H__ */

